$(function () {
    let orders = new Orders();
    $(".view-button").on("click", function () {
        $(".window-button").empty();
        orders.getOrderByOrderId($(this).attr("order-id")).then(res => {
            let orderJson = JSON.parse(res);
            console.log(orderJson)
            $(".tracking-number").text(orderJson.ordersId)
            $(".addressee").text(orderJson.address.addressName)
            $(".mobile-phone-number").text(orderJson.address.addressPhone)
            $(".delivery-address").text(orderJson.address.addressProvince +
                " " + orderJson.address.addressCity +
                " " + orderJson.address.addressDistrict +
                " " + orderJson.address.fullAddress)
            $(".total-price").text(orderJson.paymentPrice + "元")
            $(".source").text(orderJson.warehouse.warehouseName)
            if (orderJson.modeOfDelivery === 0){
                $(".shipping-method").text("公路运输")
            }else if (orderJson.modeOfDelivery === 1){
                $(".shipping-method").text("航空运输")
            }else if (orderJson.modeOfDelivery === 2){
                $(".shipping-method").text("铁路运输")
            }

            $(".go-map").attr("orders-status",orderJson.ordersStatus)
            $(".go-map").attr("companies-name",orderJson.logisticsCompanies.logisticsCompaniesName)
            $(".go-map").attr("station-longitude",orderJson.logisticsStation.logisticsStationLongitude)
            $(".go-map").attr("station-latitude",orderJson.logisticsStation.logisticsStationLatitude)
            $(".go-map").attr("station-deliveryman",orderJson.logisticsStation.logisticsStationDeliveryman)
            $(".go-map").attr("station-province",orderJson.logisticsStation.logisticsStationProvince)
            $(".go-map").attr("station-city",orderJson.logisticsStation.logisticsStationCity)
            $(".go-map").attr("station-district",orderJson.logisticsStation.logisticsStationDistrict)
            $(".go-map").attr("station-name",orderJson.logisticsStation.logisticsStationName)

            $(".go-map").attr("warehouse-name",orderJson.warehouse.warehouseName)
            $(".go-map").attr("warehouse-latitude",orderJson.warehouse.warehouseLatitude)
            $(".go-map").attr("warehouse-longitude",orderJson.warehouse.warehouseLongitude)

            $(".go-map").attr("address-name",orderJson.address.addressName)
            $(".go-map").attr("address-phone",orderJson.address.addressPhone)
            $(".go-map").attr("address-province",orderJson.address.addressProvince)
            $(".go-map").attr("address-city",orderJson.address.addressCity)
            $(".go-map").attr("address-district",orderJson.address.addressDistrict)
            $(".go-map").attr("address-latitude",orderJson.address.latitude)
            $(".go-map").attr("address-longitude",orderJson.address.longitude)
            $(".go-map").attr("address-fullAddress",orderJson.address.fullAddress)


            $(".logistics-companies").text(orderJson.logisticsCompanies.logisticsCompaniesName)
            $(".logistics-station").text(orderJson.logisticsStation.logisticsStationName)


            if (orderJson.freight === 0) {
                $(".freight").text("免运费")
            } else {
                $(".freight").text(orderJson.freight + "元")
            }
            //是否使用优惠卷
            if (orderJson.couponCredit !== 0) {
                $(".coupon-credit").text(orderJson.couponCredit + "元")
                $(".use-coupon-name").text(orderJson.coupons.couponTitle)
                $(".use-coupon-discount").text((parseFloat(orderJson.coupons.discount) / 2 * 10) + "折")
            } else {
                $(".coupon").html("<div class='use-coupon'><a>使用优惠卷 :</a>" +
                    "<span style='margin-left: 5px'>未使用优惠卷</span></div>")
            }

            let textUtil = new Text_util();
            $(".place-order-date").text(textUtil.formatDateTime(orderJson.placeOrderDate))
            if (orderJson.ordersStatus === 6) {
                $(".estimated-time-arrival").text(textUtil.formatDateTime(orderJson.estimatedTimeArrival))
                $(".order-status").text("需分拣")
                $(".window-button").append("<button class='sorting update-orders' status='"+7+"' order-id='"+orderJson.ordersId+"'>分拣</button>")
                $(".window-button").append("<button class='cancel'>取消</button>")
            } else if (orderJson.ordersStatus === 7) {
                $(".estimated-time-arrival").text(textUtil.formatDateTime(orderJson.estimatedTimeArrival))
                $(".order-status").text("需送货")
                $(".window-button").append("<button class='deliver-goods update-orders' status='"+8+"' order-id='"+orderJson.ordersId+"'>送货</button>")
                $(".window-button").append("<button class='cancel'>取消</button>")
            }else if (orderJson.ordersStatus === 8){
                $(".estimated-time-arrival").text(textUtil.formatDateTime(orderJson.estimatedTimeArrival))
                $(".order-status").text("已送达")
                $(".window-button").append("<button class='served update-orders' status='"+9+"' order-id='"+orderJson.ordersId+"'>送达</button>")
                $(".window-button").append("<button class='cancel'>取消</button>")
            }

            $(".total-number").text(orderJson.totalMerchandise)
            if (orderJson.paymentMethods === 0) {
                $(".payment-methods").text("支付宝支付")
            }

            orders.getWarehouseById(orderJson.warehouseId).then(res => {
                let recommendWarehouseJson = JSON.parse(res);
                $("#warehouse").append(`<option value="${recommendWarehouseJson.warehouseId}">
                                            ${recommendWarehouseJson.warehouseName}
                                    </option>`)
                orders.getAllWarehousesExcept(orderJson.warehouseId).then(res => {
                    let warehouseJson = JSON.parse(res);
                    for (const warehouse of warehouseJson) {
                        $("#warehouse").append(`<option value="${warehouse.warehouseId}">
                                            ${warehouse.warehouseName}
                                    </option>`)
                    }
                })
            })

            let arrNumber = orderJson.numberProducts.split(",");
            let index = 0;

            $($(".table-body")[1]).empty()
            $("#warehouse").empty()
            for (const commodity of orderJson.commodityList) {
                let gift = commodity.gifts || {commodity: {commodityName: "无", giftsNumber: 0}}
                let row = "<div class='table-row'> " +
                    "<div class='table-cell commodity-id'>" + commodity.commodityId + "</div> " +
                    "<div class='table-cell' style='width: 15%' title='" + commodity.commodityName + "'>"
                    + commodity.commodityName + "</div> " +
                    "<div class='table-cell'>" + commodity.commodityPrice + "</div> " +
                    "<div class='table-cell quantity-purchased'>" + arrNumber[index] + "</div> " +
                    "</div> " +
                    "<div class='drop-down-more'> <div style='display: flex;'> " +
                    "<div class='product-images'> " +
                    "<img src='http://localhost:8083/resource_packs/images/" +
                    commodity.commodityImages + "'" +
                    " alt='商品图片' title='" + commodity.commodityName + "'> " +
                    "</div>"
                if (commodity.gifts !== undefined) {
                    row += "<div class='product-more-detailed'> " +
                        " <div class='product-gifts'><span class='product-gifts-title'>赠品</span>" +
                        "<a class='product-gifts-name'>" + gift.commodity.commodityName + "</a>" +
                        "<span class='gifts-inventory'>库存:</span>" +
                        "<a class='gifts-inventory-number'>" + gift.giftsNumber + "</a>" +
                        " </div>"
                }
                row += "<div class='specification'>" + commodity.commodityName
                if (commodity.commoditySpecification !== undefined) {
                    for (const commoditySpecification of commodity.commoditySpecification) {
                        row += "&nbsp;<span class='specification-name'>" +
                            commoditySpecification.specificationName
                            + "</span>"
                    }
                }
                row += "<div class='insurance'>"
                if (commodity.commodityInsurances !== undefined) {
                    for (const commodityInsurance of commodity.commodityInsurances) {
                        row += "<span class='insurance-title'>" + commodityInsurance.insuranceTitle + "</span>"
                    }
                }
                row += "<div class='warehouse'><a class='product-inventory-title'>商品库存:</a><span class='product-inventory'>" +
                    commodity.commodityWarehouse.detailsInventory
                    + "</span><a class='purchase-limit-title'>商品限购:</a><span class='purchase-limit'>" +
                    commodity.commodityWarehouse.purchaseLimit +
                    "</span></div>"
                row += "</div></div>"

                row += "</div></div>"
                $($(".table-body")[1]).append(row)
                index++;
            }
            $($(".window")[0]).css("display", "block")
            $(".orders-table-body .table-row ").on("click", function () {
                $(this).next().stop().slideToggle();
            });
            $(".shipments").on("click", function () {
                // console.log($("#warehouse").val())
                for (let i = 0; i < $(".product-inventory").length; i++) {

                    let inventory = $($(".product-inventory")[i]).text();
                    let quantity = $($(".quantity-purchased")[i]).text();
                    let commodityId = $($(".commodity-id")[i]).text();
                    let shippingMethod = $("#shipping-method").val()
                    let logisticsCompanies = $(".logistics-companies").val()
                    let logisticsStation = $("#logistics-station").val();

                    console.log((parseInt(inventory) - parseInt(quantity)))
                    if (parseInt(inventory) > parseInt(quantity)) {
                        console.log(commodityId)

                        orders.ordersShipments(commodityId, (parseInt(inventory) - parseInt(quantity)),
                            shippingMethod, logisticsCompanies, logisticsStation, $(".tracking-number").text()).then(res => {
                            console.log(res)
                            if (textUtil.clearSpaces(res) === "true") {
                                location.reload();
                            }
                        })
                    } else {
                        alert("超过库存！")
                        return;
                    }
                }
            })
            $("#warehouse").on("change", function () {
                let warehouseId = $(this).val();
                let orderId = $(".tracking-number").text();
                orders.updateWarehouseIdByOrderId(orderId, warehouseId).then(res => {
                    console.log(res)
                    location.reload();
                })
            })
            $(".cancel").on("click", function () {
                $(".window").css("display", "none")
            })
            $(".pop-ups-down").on("click",function () {
                $(".window").css("display", "none")
            })
            $(".update-orders").on("click",function () {
                let orderId = $(this).attr("order-id");
                let status = $(this).attr("status");
                orders.updateOrderStatusByOrderId(orderId,status).then(res=>{
                    console.log(res)
                    location.reload();
                })
            })
        })
    })
    $(".inquire-button").on("click", function () {
        let nameOrId = $(".nameOrId").val();
        let currentPage = $(".sift-function").attr("current-page");
        let totalPages = $(".sift-function").attr("page-size");
        let dateSort = $(".chronological-ordering:checked").val()
        let state = $("#state").val();
        orders.orderManagement(dateSort, currentPage, totalPages, state,nameOrId,104).then(res => {
            // 提取返回的 HTML 页面中 <body> 标签的内容
            let bodyContent = $("<div>").html(res).find(".son-body");

            // 将内容替换到指定元素中
            $(".son-body").html(bodyContent.html());
            $.getScript("/www.xiaomi.com/other/component/jquery.min.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/logistics.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/home.js");
        })
    })
    $(".search-img").on("click",function () {
        let nameOrId = $(".nameOrId").val();
        let currentPage = $(".sift-function").attr("current-page");
        let totalPages = $(".sift-function").attr("page-size");
        let dateSort = $(".chronological-ordering:checked").val()
        let state = $("#state").val();
        orders.orderManagement(dateSort, currentPage, totalPages, state,nameOrId,104).then(res => {
            // 提取返回的 HTML 页面中 <body> 标签的内容
            let bodyContent = $("<div>").html(res).find(".son-body");

            // 将内容替换到指定元素中
            $(".son-body").html(bodyContent.html());
            $.getScript("/www.xiaomi.com/other/component/jquery.min.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/logistics.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/home.js");
        })
    })
    $(".go-map").on("click",function () {
        window.open("http://localhost:8083/www.xiaomi.com/background/map?companiesName="+
            $(this).attr("companies-name")+"&ordersStatus="+$(this).attr("orders-status")+"&stationLongitude="
            +$(this).attr("station-longitude")+"&stationLatitude="+$(this).attr("station-latitude")+"&stationDeliveryman="
            +$(this).attr("station-deliveryman")+"&stationProvince="+$(this).attr("station-province")+"&stationCity="
            +$(this).attr("station-city")+"&stationDistrict="+$(this).attr("station-district")+"&stationName="
            +$(this).attr("station-name")+"&warehouseName="+$(this).attr("warehouse-name")+"&warehouseLatitude="
            +$(this).attr("warehouse-latitude")+"&warehouseLongitude="+$(this).attr("warehouse-longitude")+"&addressName="
            +$(this).attr("address-name")+"&addressPhone="+$(this).attr("address-phone")+"&addressProvince="
            +$(this).attr("address-province")+"&addressCity="+$(this).attr("address-city")+"&addressDistrict="
            +$(this).attr("address-district")+"&addressLatitude="+$(this).attr("address-latitude")+"&addressLongitude="
            +$(this).attr("address-longitude")+"&addressFullAddress="+$(this).attr("address-fullAddress")
            , "_blank")
    })
})

